package com.topdt.jbpm.web.struts.action;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.common.web.ActionResult;
import com.topdt.jbpm.form.TemplateCreater;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.model.Form;
import com.topdt.jbpm.service.ApplicationService;
import com.topdt.jbpm.service.FormService;

/**
 *  @Project       : thx-workflow
 *  @Program Name  : com.topdt.jbpm.web.struts.action.FormAction.java
 *  @Class Name    : FormAction
 *  @Description   : 表单相关
 *  @Author        : calonlan
 *  @Creation Date : 2015年2月2日 下午2:33:39
 *  @ModificationHistory
 *  Who        When          What
 *  --------   ----------    -----------------------------------
 *  username   2015年2月2日       TODO
 */
@Namespace("/workflow")
@Action(value = "form",
		results = {
		@Result(name = "list", location = "/workflow/flow/list.jsp"),
		@Result(name = "formTemplate",location = "/workflow/app/form-template.jsp"),
		@Result(name = "preview", location = "/workflow/app/preview.jsp"),
		@Result(name = "json", type = "json", params = { "root", "result" })
		}
)
@Controller
@Scope("prototype")
public class FormAction extends CurdAction<Form> {

  private static final long serialVersionUID = 1L;
  @Autowired
	private ApplicationService applicationService;
	@Autowired
	private FormService formService;
	private String appId;
	
	private String template;
    
    public String getTemplate() {
        return template;
    }

    public void setTemplate(String template) {
      this.template = template;
    }

	private List<String> listString;

	
	/**
	 *  @Description    : 方法描述
	 *  @Method_Name    : getHtml
	 *  @return
	 *  @return         : String
	 *  @Creation Date  : 2015年2月2日 下午4:58:44
	 *  @version        : v1.00
	 *  @Author         : calonlan

	 *  @Update Date    : 2015年2月2日 下午4:58:44
	 *  @Update Author  : calonlan
	 */
	public void getHtml() {
		logger.debug("<进入>:getHtml方法   获得表单");
		Application application = applicationService.get(appId);
		String formId = application.getForm().getFormId();
		Form form = formService.get(formId);
		String tableHTML = "";
		if(form!=null || !"".equals(form)){
			if(form.getTempletStorageType()!=null && !"".equals(form.getTempletStorageType()) && "byte".equals(form.getTempletStorageType())){
			  if(form.getTempletByte() != null && form.getTempletByte().length > 0) {
			    InputStreamReader templetByte;
			    try {
			      templetByte = new InputStreamReader(new ByteArrayInputStream(form.getTempletByte()),"utf-8");
			    } catch (UnsupportedEncodingException e) {
			      templetByte = new InputStreamReader(new ByteArrayInputStream(form.getTempletByte()));
			      e.printStackTrace();
			    }
			    char[] b = new char[1024];
			    String byteHtml = "";
			    //变成string
			    while(true){
			      int bytesRead = 0;
			      try {
			        bytesRead = templetByte.read(b, 0, 1024);
			      } catch (IOException e) {
			        logger.error("<错误>:获得表单失败",e);
			      }
			      if(bytesRead!=-1){
			        byteHtml += new String(b,0,bytesRead);
			      }else if(bytesRead==-1){
			        break;
			      }
			    }
			    Document doc = Jsoup.parse(byteHtml, "UTF-8");
			    Element table = doc.getElementsByTag("table").first();
			    tableHTML = "<table  style=\"width:100%;\" cellpadding=\"2\" cellspacing=\"0\" border=\"1\" bordercolor=\"#000000\">";
			    for (Element tr : table.getElementsByTag("tr")) {
			    	String trStr = "<tr>";
			    	for (Element th : tr.getElementsByTag("th")) {
			    		if(!"&nbsp;".equals(th.html())){
			    			String display = "style=\"" + th.attr("style") + "\"";
			    			String fieldText = th.text();
			    			String input = th.nextElementSibling().getElementsByClass("form-content").get(0).html();
			    			String itemDiv = String.format(TemplateCreater.FILED_FORMAT, display, fieldText, input);
			    			trStr += "<th>" + itemDiv + "</th>";
			    		}else{
			    			trStr += "<th>&nbsp;</th>";
			    		}
					}
			    	trStr += "</tr>";
			    	tableHTML += trStr;
				}
			    tableHTML += "</table>";
			  }
			}else if("file".equals(form.getTempletStorageType())){
				if(form.getTempletPath()!=null && !"".equals(form.getTempletPath())){
					tableHTML = TemplateCreater.getTableHtmlByForm(form);
				}
			}
		}
		tableHTML = com.alibaba.fastjson.JSON.toJSONString(tableHTML);
		try {
			writeJson(tableHTML);
		} catch (IOException e) {
			logger.error("<错误>:获得表单失败",e);
			setResult(ActionResult.FAIL, "服务器异常！");
		}
	}


	public String show(){
		logger.debug("<进入>:show方法 ");
		//获取对应的字段名
		Application application = applicationService.get(appId);
		String formId = application.getForm().getFormId();
		Form form = formService.get(formId);
		if(form!=null || !"".equals(form)){
			listString = TemplateCreater.listFieldHtml(form);
		}
		return "formTemplate";
	}


	public void saveHtml(){
		logger.debug("<进入>:saveHtml方法   保存表单");
		String json = "";
		try {
			//getRequest().setCharacterEncoding("utf-8");
			String HTMLSource = getRequest().getParameter("HTMLSource");
			HTMLSource = HTMLSource.replaceAll("~", "%");
			HTMLSource = URLDecoder.decode(HTMLSource, "UTF-8");
			HTMLSource =HTMLSource.replaceAll("\\^", "\'");
			//获取appId,formId
			Application application = applicationService.get(appId);
			String formId = application.getForm().getFormId();
			Form form = formService.get(formId);
			if(form!=null || !"".equals(form)){
		     	String mobileTemplate =TemplateCreater.createMobileTemplate(form);
				form.setFormId(form.getFormId());
				form.setTempletByte(HTMLSource.getBytes("utf-8"));
				form.setTempletStorageType(Form.TempletStorageType_BYTE);
				form.setMobileTemplateByte(mobileTemplate.getBytes("utf-8"));
				formService.save(form);
				json = "生成表单成功";
			}
		} catch (Exception e) {
			logger.error("<错误>:保存表单失败", e);
		}
		try {
          writeJson(json);
        } catch (IOException e) {
            logger.error("<错误>:"+e.getMessage());
            setResult(ActionResult.FAIL, "服务器异常！");
        }
	}

	public String createTemplate(String htmlSource){
		logger.debug("<进入>:createTemplate方法");
		String	contextPath =  ServletActionContext.getServletContext().getRealPath(java.io.File.separator);
		if(StringUtils.isBlank(contextPath)){
			contextPath =  ServletActionContext.getServletContext().getRealPath("/");
		}
		String temPath = contextPath+ java.io.File.separator+AppContext.getProperties("formTemplatePath");
		File folder = new File(temPath);
		File temp = new File(folder,"template.html");
		if(!temp.exists())
			return "系统模板不存在！";
		String tempString = "";
		try {
			Document doc = Jsoup.parse(temp, "UTF-8", "");
			Element div = doc.getElementById("form-Tem");
			div.append(htmlSource);
			tempString = doc.html();
		} catch (IOException e) {
			logger.error("<错误>:"+e.getMessage());
		}
		return tempString;
	}

	public String preview(){
      logger.debug("<进入>:preview方法");
      try {
          String HTMLSource = getRequest().getParameter("htmlSource");
          
          HTMLSource = HTMLSource.replaceAll("~", "%");
          HTMLSource = URLDecoder.decode(HTMLSource, "UTF-8");
          HTMLSource =HTMLSource.replaceAll("\\^", "\'");
          
          String appId = getRequest().getParameter("appId");
          Application application = applicationService.get(appId);
          String htmlSource = createTemplate(HTMLSource);
          String htmlSource1 = htmlSource.substring(htmlSource.indexOf("<div id=\"form_Content\">"), htmlSource.indexOf(" <div id=\"docWord\" style=\"display:none;\">"))
                               .replace("!''", "");
          String htmlSource2 = htmlSource.substring(htmlSource.indexOf("<div id=\"attachePanel\">"), htmlSource.indexOf("</body>"))
                               .replace("!''", "");
          htmlSource = htmlSource1 + htmlSource2;
          String hValue = htmlSource.substring(htmlSource.indexOf("<h1>")+4, htmlSource.indexOf("</h1>"));
          htmlSource = htmlSource.replace(hValue, application.getAppName());
          String[] s = htmlSource.split("\\u0024\\u007B");
          String newTemplate = "";
          for(int i = 0; i<s.length; i++){
              if(i==0){
                  newTemplate+=s[0];                  
              }else{
                  String[] s1 = s[i].split("}");
                  for(int j = 0; j<s1.length; j++){
                      if(j>0 && j==s1.length-1){
                          newTemplate+=s1[j];                         
                      }
                  }
              }
          }
          template = newTemplate;
      } catch (Exception e) {
          logger.error("<错误>:"+e.getMessage());
          e.printStackTrace();
      }
      return "preview";
  }
	public String getAppId() {
		return appId;
	}


	public void setAppId(String appId) {
		this.appId = appId;
	}


	public List<String> getListString() {
		return listString;
	}


	public void setListString(List<String> listString) {
		this.listString = listString;
	}

}
